import systemConfig from "@/system.config.js";
import Storage from "@/js/storage.js";
import {Message} from "element-ui";
import {emitEvent} from "@/js/EventBus.js";

/**
 * 判断是否登录
 * @returns {boolean} true:已登录；false:未登录，并提示请先登录
 */
function isLogin(){
    if (!Storage.has("token")) {
        Message.error("请先登录!");
        emitEvent("showLogin", {from: "请先登录!"})
        return false;
    }
    return true
}
/**
 * 判断用户类型
 */
function judgeUserType(){
    let token = Storage.get("token");
    if (!token){
        return systemConfig.userType.NON_USER;
    }
    let JWTObj = parseJwt(token);
    let userinfo = JWTObj.userinfo;

    if (userinfo.userType  === systemConfig.userType.ADMIN){
        return systemConfig.userType.ADMIN;
    }
    return systemConfig.userType.USER;
}

/**
 * 解析JWT
 * @param token
 * @returns {Object|null} 解析出的JWT对象
 */
function parseJwt(token) {
    try {
        if(!token){
            return null;
        }
        // 拆分Token
        const parts = token.split('.');
        if (parts.length !== 3) {
            console.error("无效的JWT格式")
            return null;
        }

        // 获取Payload部分
        const base64Url = parts[1];

        // 处理Base64Url并补充填充
        let base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
        const padLength = (4 - (base64.length % 4)) % 4;
        base64 += '='.repeat(padLength);

        // 解码并处理URI编码
        const decoded = atob(base64);
        const jsonPayload = decodeURIComponent(
            decoded.split('').map(c =>
                '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
            ).join('')
        );

        return JSON.parse(jsonPayload);
    } catch (error) {
        console.error('解析JWT失败:', error);
        return null;
    }
}

export default {
    judgeUserType,
    parseJwt,
    isLogin
}
